package com.huaxonline.boot.web.pojo.response;

import com.huaxonline.boot.web.constant.IResponseEnum;
import com.huaxonline.boot.web.constant.enums.CommonResponseEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.ToString;

/**
 * 通用返回结果，同{@link CommonResponse}
 *
 * @param <T>
 * @author sprainkle
 * @date 2019/5/2
 * @see CommonResponse
 */
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@Schema(description = "响应主体")
public class R<T> extends CommonResponse<T> {

    public R() {
        super();
    }

    public R(T data) {
        super();
        this.data = data;
    }

    public R(T data, String msg) {
        super();
        this.data = data;
        this.message = msg;
    }

    public R(Throwable e) {
        super();
        this.message = e.getMessage();
        this.code = -1;
    }

    public R data(T data) {
        this.data = data;
        return this;
    }

    public static <T> R<T> ok() {
        return restResult(CommonResponseEnum.SUCCESS);
    }

    public static <T> R<T> ok(String msg) {
        return restResult(CommonResponseEnum.SUCCESS.getCode(), msg);
    }

    public static <T> R<T> ok(T data) {
        return restResult(CommonResponseEnum.SUCCESS, data);
    }

    public static <T> R<T> ok(String msg, T data) {
        return restResult(CommonResponseEnum.SUCCESS.getCode(), msg, data);
    }

    public static <T> R<T> failed() {
        return restResult(CommonResponseEnum.FAIL);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(CommonResponseEnum.FAIL.getCode(), msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(CommonResponseEnum.FAIL, data);
    }

    public static <T> R<T> failed(String msg, T data) {
        return restResult(CommonResponseEnum.FAIL.getCode(), msg, data);
    }

    public static <T> R<T> failed(IResponseEnum iResponseEnum) {
        return restResult(iResponseEnum);
    }

    public static <T> R<T> failed(IResponseEnum iResponseEnum, T data) {
        return restResult(iResponseEnum, data);
    }

    public static <T> R<T> restResult(IResponseEnum iResponseEnum) {
        return restResult(iResponseEnum.getCode(), iResponseEnum.getMessage());
    }

    public static <T> R<T> restResult(IResponseEnum iResponseEnum, T data) {
        return restResult(iResponseEnum.getCode(), iResponseEnum.getMessage(), data);
    }

    private static <T> R<T> restResult(int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setMessage(msg);
        return apiResult;
    }

    private static <T> R<T> restResult(int code, String msg, T data) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMessage(msg);
        return apiResult;
    }
}
